import React, { createContext, useCallback, useContext, useMemo } from 'react';
import { notification  } from 'antd';
import { ExclamationCircleFilled, CloseCircleFilled, CheckCircleFilled, WarningFilled } from '@ant-design/icons'

// 创建通知上下文
const NotificationContext = createContext();

// 通知提供者组件
export const NotificationProvider = ({ children }) => {
  const [api, contextHolder] = notification.useNotification();
  // 封装打开通知的方法一  useCallback
  const openNotification = useCallback((description='通知描述', type='tips',  placement='topRight', message='') => {
    api.info({
      description,
      icon: getIcon(type),
      placement,
      message,
      duration: 1
    });
  },[api]) ;
  const contextValue = useMemo(() => ({ openNotification }), [openNotification]);

  // 封装打开通知的方法二  useMemo 
  // const contextValue = useMemo(() => {
  //   const openNotification = (description='通知描述', type='tips', placement='topRight', message='') => {
  //     api.info({
  //       description,
  //       icon: getIcon(type),
  //       placement,
  //       message,
  //     });
  //   };
  //   return { openNotification };
  // }, [api]);

  return (
    <NotificationContext.Provider value={contextValue}>
      {contextHolder}
      {children}
    </NotificationContext.Provider>
  );
};

// 获取通知上下文的钩子函数
export const useNotification = () => {
  return useContext(NotificationContext);
};


const getIcon = (type) => {
  switch (type) {
    case 'success':
      return <CheckCircleFilled style={{ color: '#57C470' }}/>
    case 'fail':
      return <CloseCircleFilled style={{ color: '#FD5B5B' }}/>
    case 'warning':
      return <WarningFilled style={{ color: '#FBC015' }}/>
    default:
      return <ExclamationCircleFilled style={{ color: '#2878FF' }}/>
  }
}